import { observer } from 'mobx-react'
import { useState, useEffect } from 'react'
import type { PopconfirmProps } from 'antd'
import { Input, Select, Button, Table, DatePicker, Popconfirm, message } from 'antd'
import { SearchOutlined } from '@ant-design/icons'
import type { ColumnsType } from 'antd/es/table'
import './filter.less'
import resetImg from '@/assets/images/filter/reset.png'
import dayjs from 'dayjs'
import { getAppVersionList } from '@/apis/appVersionManagement'
import { useNavigate } from 'react-router-dom'

const { RangePicker } = DatePicker

interface DataType {
  key: string;
  serialNumber: number;
  productName: string;
  platform: string;
  version: string;
  status: string;
  updateDescription: string;
  downloadUrl: string;
  operator: string;
  operationTime: string;
}

// 定义筛选表单的接口
interface FilterForm {
  productName: string;
  platform: string | null;
  version: string | null;
  forceUpdate: string | null;
  operator: string;
  dateRange: [string, string] | null;
}

// 初始化表单状态
const initialFilterForm: FilterForm = {
  productName: '',
  platform: null,
  version: null,
  forceUpdate: null,
  operator: '',
  dateRange: null,
}

const AppVersionManagement: React.FC = () => {
  const [filterForm, setFilterForm] = useState<FilterForm>(initialFilterForm)
  const [data, setData] = useState<DataType[]>([])
  const [loading, setLoading] = useState(false)
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  })
  const navigate = useNavigate()

  // 获取列表数据
  const fetchData = async (params = {}) => {
    try {
      setLoading(true)
      const response = await getAppVersionList({
        ...filterForm,
        current: pagination.current,
        pageSize: pagination.pageSize,
        ...params
      })
      if (response.code === 200) {
        // 为每条数据添加唯一的 key
        const listWithKeys = response.data.list.map((item: any) => ({
          ...item,
          key: item.id.toString()
        }))
        setData(listWithKeys)
        setPagination(prev => ({
          ...prev,
          total: response.data.total
        }))
      } else {
        message.error(response.message || '获取数据失败')
      }
    } catch (error) {
      console.error('获取数据失败:', error)
      message.error('获取数据失败')
    } finally {
      setLoading(false)
    }
  }

  // 页面初始化时获取数据
  useEffect(() => {
    fetchData()
  }, [])

  // 处理表单字段变化
  const handleFormChange = (field: keyof FilterForm, value: any) => {
    setFilterForm(prev => ({
      ...prev,
      [field]: value
    }))
  }

  // 搜索事件处理
  const handleSearch = async () => {
    try {
      const { dateRange, ...rest } = filterForm
      const params = {
        ...rest,
        current: 1,
        pageSize: pagination.pageSize,
        startTime: dateRange?.[0] || undefined,
        endTime: dateRange?.[1] || undefined,
      }

      setPagination(prev => ({ ...prev, current: 1 }))
      await fetchData(params)
    } catch (error) {
      console.error('查询失败:', error)
      message.error('查询失败')
    }
  }

  // 重置表单事件处理
  const handleReset = () => {
    setFilterForm(initialFilterForm)
    setPagination(prev => ({ ...prev, current: 1 }))
    fetchData({
      ...initialFilterForm,
      current: 1,
      pageSize: pagination.pageSize
    })
  }

  // 处理表格分页、排序、筛选变化
  const handleTableChange = (newPagination: any) => {
    setPagination(prev => ({
      ...prev,
      current: newPagination.current,
      pageSize: newPagination.pageSize
    }))
    fetchData({
      current: newPagination.current,
      pageSize: newPagination.pageSize
    })
  }

  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      // 序号自增
      render: (_, record, index) => index + 1,
    },
    {
      title: '产品名称',
      dataIndex: 'productName',
      key: 'productName',
    },
    {
      title: '平台',
      dataIndex: 'platform',
      key: 'platform',
    },
    {
      title: '版本号',
      dataIndex: 'version',
      key: 'version',
    },
    {
      title: '状态',
      dataIndex: 'forceUpdate',
      key: 'forceUpdate',
    },
    {
      title: '更新描述',
      dataIndex: 'updateDescription',
      key: 'updateDescription',
    },
    {
      title: '下载地址',
      dataIndex: 'downloadUrl',
      key: 'downloadUrl',
      render: (text: string) => (
        <a style={{ color: '#02A7F0', textDecoration: 'underline' }}>{text}</a>
      )
    },
    {
      title: '操作人',
      dataIndex: 'operator',
      key: 'operator',
    },
    {
      title: '操作时间',
      dataIndex: 'operationTime',
      key: 'operationTime',
    },
    {
      title: '操作',
      key: 'action',
      width: 160,
      render: (record) => (
        <div className='table-cell-actions'>
          <Button type="link" onClick={() => handleEdit(record)}>修改</Button>
          <Popconfirm
            title="提示"
            description="是否删除？"
            onConfirm={confirm}
            onCancel={cancel}
            okText="是的"
            cancelText="取消"
          >
            <Button type="link">删除</Button>
          </Popconfirm>
        </div>
      ),
    },
  ]
  const handleEdit = (record: DataType) => {
    navigate('/setting/appVersionManagement/edit', { state: { record } })
  }
  const handleAdd = () => {
    navigate('/setting/appVersionManagement/add')
  }
  const confirm: PopconfirmProps['onConfirm'] = (e) => {
    console.log(e)
    message.success('点击确定')
  }
  const cancel: PopconfirmProps['onCancel'] = (e) => {
    console.log(e)
    message.error('点击取消')
  }
  return (
    <div className="app-container">
      <div className="filterForm">
        <div className="form">
          <div className="field">
            <div className="label">产品名称</div>
            <div className="value">
              <Input 
                allowClear
                placeholder="请输入产品名称"
                value={filterForm.productName}
                onChange={e => handleFormChange('productName', e.target.value)}
                suffix={<span />}
              />
            </div>
          </div>
          <div className="field">
            <div className="label">平台</div>
            <div className="value">
              <Select
                allowClear
                placeholder="请选择平台"
                style={{ width: '100%' }}
                value={filterForm.platform}
                onChange={value => handleFormChange('platform', value)}
              >
                <Select.Option value="android">Android</Select.Option>
                <Select.Option value="ios">IOS</Select.Option>
              </Select>
            </div>
          </div>
          <div className="field">
            <div className="label">版本号</div>
            <div className="value">
              <Select 
                placeholder="请选择版本号" 
                style={{ width: '100%' }}
                value={filterForm.version}
                onChange={value => handleFormChange('version', value)}
              >
                <Select.Option value="v1.0.0">v1.0.0</Select.Option>
                <Select.Option value="v2.0.0">v2.0.0</Select.Option>
              </Select>
            </div>
          </div>
          <div className="field">
            <div className="label">强制更新</div>
            <div className="value">
              <Select 
                placeholder="请选择是否强制更新" 
                style={{ width: '100%' }}
                value={filterForm.forceUpdate}
                onChange={value => handleFormChange('forceUpdate', value)}
              >

                <Select.Option value="1">是</Select.Option>
                <Select.Option value="0">否</Select.Option>
              </Select>
            </div>
          </div>
          <div className="field">
            <div className="label">操作人</div>
            <div className="value">
              <Input 
                placeholder="请输入操作人账号"
                value={filterForm.operator}
                onChange={e => handleFormChange('operator', e.target.value)}
                suffix={<span />}
              />
            </div>
          </div>
          <div className="field">
            <div className="label">操作时间</div>
            <div className="value">
              <RangePicker 
                style={{ width: '100%' }}
                value={filterForm.dateRange ? [
                  dayjs(filterForm.dateRange[0]),
                  dayjs(filterForm.dateRange[1])
                ] : null}
                onChange={(dates, dateStrings) => 
                  handleFormChange('dateRange', dates ? dateStrings : null)
                }
              />
            </div>
          </div>
        </div>
        <div className="rightAction">
          <Button type="primary" onClick={handleSearch}>
            <SearchOutlined />
            查询
          </Button>
          <Button onClick={handleReset}>
            <img src={resetImg} alt="reset" />
            重置
          </Button>
        </div>
      </div>

      <div className="table-operations">
        <Button type="primary" onClick={handleAdd}>+ 新增</Button>
        <Button>刷新缓存</Button>
      </div>

      <Table
        columns={columns}
        dataSource={data}
        pagination={{
          ...pagination,
          showSizeChanger: true,
          showTotal: (total) => `共 ${total} 条`,
        }}
        loading={loading}
        onChange={handleTableChange}
      />
    </div>
  )
}

export default observer(AppVersionManagement)